﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Data.EntityClasses;
using NetDon.OA.Interface.Admin;
using NetDon.Utilities;

namespace NetDon.OA.Portal
{
    public class PositionDropDown : DropDownList
    {
        public PositionDropDown()
            : base()
        {
            this.Items.Clear();
            this.Items.AddRange(GetItems());
            this.Items.Insert(0, new ListItem(EnumUtilities.GetDescription(ListEmptyType.Select), string.Empty));
        }

        public override string DataTextField
        {
            get { return "PostName"; }
            set { base.DataTextField = value; }
        }

        public override string DataValueField
        {
            get { return "PostId"; }
            set { base.DataValueField = value; }
        }

        public ListItem[] GetItems()
        {
            var postService = ServiceContainer.GetService<IPostService>();
            var rootPositions = postService.GetRootPosts();
            List<PostData> newPostEnties = new List<PostData>();
            foreach (var rootPosition in rootPositions)
            {
                newPostEnties.Add(new PostData() { PostId = rootPosition.PostId, PostName = rootPosition.PostName });
                LoadPositions(rootPosition.PostId, newPostEnties);
            }

            ListItem[] lists = new ListItem[0];
            foreach (var postData in newPostEnties)
            {
                Array.Resize<ListItem>(ref lists, lists.Length + 1);
                lists[lists.Length - 1] = new ListItem(postData.PostName, postData.PostId.ToString());
            }

            return lists;
        }

        private void LoadPositions(Guid parentId, List<PostData> newPostEntities)
        {
            var postService = ServiceContainer.GetService<IPostService>();
            var childPosts = postService.GetChildPosts(parentId);
            foreach (var postEntity in childPosts)
            {
                newPostEntities.Add(new PostData() { PostId = postEntity.PostId, PostName = "|" + postEntity.PostName.PadLeft(postEntity.PostName.Length + 2 * (postEntity.NodeLevel.Value - 1), '-') });
                LoadPositions(postEntity.PostId, newPostEntities);
            }
        }
    }
}